<?php namespace Common\Model;
use Hdphp\Model\Model;
class Admin extends Model{
	protected $table = 'admin';
//	注册信息的自动验证
	protected $validate = array(
		array('username','required','用户名不能为空',3,3),
		array('password','required','密码不能为空',3,3),
	);
//	自动完成注册时间
	protected $auto = array(
		array('logintime','time','function',3,1)
	);
	
//	管理员登陆
	public function login(){
//		自动完成验证
		if(!$this->create()) return false;
//  		获得提交过来的数据
		$username = Q('post.username');
		$password = Q('post.password','','md5');
//		判断验证码
		/*if(Q('post.verify','','strtoupper')!=Code::get()){
			$this->error = '验证码错误';
			return false;
		}*/
//		获得数据
		$userData = $this->where("username = '{$username}'")->find();
//		判断用户是否存在
		if(!$userData){
			$this->error = '用户名不存在！';
			return false;
		};
//		判定密码是否正确
		if($userData['password']!=$password){
			$this->error = '密码错误！';
			return FALSE;
		};
//		获得并记录上次登陆时间
		$_SESSION['lastlogintime'] = isset($userData['logintime'])?$userData['logintime']:0;
//		更新登陆时间
		$this->save(array('aid'=>$userData['aid'],'logintime'=>$this->data['logintime']));
		
//		存session
		$_SESSION['aid'] = $userData['aid'];
		$_SESSION['adminname'] = $userData['username'];
//		本次登陆时间
//		$_SESSION['thislogintime'] = $this->data['logintime'];
//		显示登陆成功，返回true
		return TRUE;
	}
	
//	添加用户
	public function store(){
		$data = Q('post.');
		if($data['password']!=$data['cpassword']){
			$this->error = '两次密码不一致';
			return FALSE;
		}
		if($this->where("username = '{$data['username']}'")->find()){
			$this->error = '该用户名已存在';
			return FALSE;
		}
		$this->data = array(
			'username'=>$data['username'],
			'relname' =>$data['relname'],
			'password' =>md5($data['password'])
		);
		$aid = $this->add();
		$role = array(
			'role_id'=>$data['role_id'],
			'user_id'=>$aid
		);
		Db::table('user_role')->insert($role);
		return true;
	}
	
	
}
 ?>